(bug 34762) Calling close() on a DatabaseBase object now clears the connection. Based...
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * Database abstraction object for mySQL
11 * Inherit all methods and properties of Database::Database()
12 *
13 * @ingroup Database
14 * @see Database
15 */
16 class DatabaseMysql extends DatabaseBase {
17
18 /**
19 * @return string
20 */
21 function getType() {
22 return 'mysql';
23 }
24
25 /**
26 * @param $sql string
27 * @return resource
28 */
29 protected function doQuery( $sql ) {
30 if( $this->bufferResults() ) {
31 $ret = mysql_query( $sql, $this->mConn );
32 } else {
33 $ret = mysql_unbuffered_query( $sql, $this->mConn );
34 }
35 return $ret;
36 }
37
38 /**
39 * @param $server string
40 * @param $user string
41 * @param $password string
42 * @param $dbName string
43 * @return bool
44 * @throws DBConnectionError
45 */
46 function open( $server, $user, $password, $dbName ) {
47 global $wgAllDBsAreLocalhost;
48 wfProfileIn( __METHOD__ );
49
50 # Load mysql.so if we don't have it
51 wfDl( 'mysql' );
52
53 # Fail now
54 # Otherwise we get a suppressed fatal error, which is very hard to track down
55 if ( !function_exists( 'mysql_connect' ) ) {
56 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
57 }
58
59 # Debugging hack -- fake cluster
60 if ( $wgAllDBsAreLocalhost ) {
61 $realServer = 'localhost';
62 } else {
63 $realServer = $server;
64 }
65 $this->close();
66 $this->mServer = $server;
67 $this->mUser = $user;
68 $this->mPassword = $password;
69 $this->mDBname = $dbName;
70
71 wfProfileIn("dbconnect-$server");
72
73 # The kernel's default SYN retransmission period is far too slow for us,
74 # so we use a short timeout plus a manual retry. Retrying means that a small
75 # but finite rate of SYN packet loss won't cause user-visible errors.
76 $this->mConn = false;
77 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
78 $numAttempts = 2;
79 } else {
80 $numAttempts = 1;
81 }
82 $this->installErrorHandler();
83 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
84 if ( $i > 1 ) {
85 usleep( 1000 );
86 }
87 if ( $this->mFlags & DBO_PERSISTENT ) {
88 $this->mConn = mysql_pconnect( $realServer, $user, $password );
89 } else {
90 # Create a new connection...
91 $this->mConn = mysql_connect( $realServer, $user, $password, true );
92 }
93 #if ( $this->mConn === false ) {
94 #$iplus = $i + 1;
95 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
96 #}
97 }
98 $phpError = $this->restoreErrorHandler();
99 # Always log connection errors
100 if ( !$this->mConn ) {
101 $error = $this->lastError();
102 if ( !$error ) {
103 $error = $phpError;
104 }
105 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
106 wfDebug( "DB connection error\n" );
107 wfDebug( "Server: $server, User: $user, Password: " .
108 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
109 }
110
111 wfProfileOut("dbconnect-$server");
112
113 if ( $dbName != '' && $this->mConn !== false ) {
114 wfSuppressWarnings();
115 $success = mysql_select_db( $dbName, $this->mConn );
116 wfRestoreWarnings();
117 if ( !$success ) {
118 $error = "Error selecting database $dbName on server {$this->mServer} " .
119 "from client host " . wfHostname() . "\n";
120 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
121 wfDebug( $error );
122 }
123 } else {
124 # Delay USE query
125 $success = (bool)$this->mConn;
126 }
127
128 if ( $success ) {
129 // Tell the server we're communicating with it in UTF-8.
130 // This may engage various charset conversions.
131 global $wgDBmysql5;
132 if( $wgDBmysql5 ) {
133 $this->query( 'SET NAMES utf8', __METHOD__ );
134 } else {
135 $this->query( 'SET NAMES binary', __METHOD__ );
136 }
137 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
138 global $wgSQLMode;
139 if ( is_string( $wgSQLMode ) ) {
140 $mode = $this->addQuotes( $wgSQLMode );
141 $this->query( "SET sql_mode = $mode", __METHOD__ );
142 }
143
144 // Turn off strict mode if it is on
145 } else {
146 $this->reportConnectionError( $phpError );
147 }
148
149 $this->mOpened = $success;
150 wfProfileOut( __METHOD__ );
151 return $success;
152 }
153
154 /**
155 * @return bool
156 */
157 function close() {
158 $this->mOpened = false;
159 if ( $this->mConn ) {
160 if ( $this->trxLevel() ) {
161 $this->commit( __METHOD__ );
162 }
163 $ret = mysql_close( $this->mConn );
164 $this->mConn = false;
165 return $ret;
166 } else {
167 return true;
168 }
169 }
170
171 /**
172 * @param $res ResultWrapper
173 * @throws DBUnexpectedError
174 */
175 function freeResult( $res ) {
176 if ( $res instanceof ResultWrapper ) {
177 $res = $res->result;
178 }
179 wfSuppressWarnings();
180 $ok = mysql_free_result( $res );
181 wfRestoreWarnings();
182 if ( !$ok ) {
183 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
184 }
185 }
186
187 /**
188 * @param $res ResultWrapper
189 * @return object|stdClass
190 * @throws DBUnexpectedError
191 */
192 function fetchObject( $res ) {
193 if ( $res instanceof ResultWrapper ) {
194 $res = $res->result;
195 }
196 wfSuppressWarnings();
197 $row = mysql_fetch_object( $res );
198 wfRestoreWarnings();
199 if( $this->lastErrno() ) {
200 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
201 }
202 return $row;
203 }
204
205 /**
206 * @param $res ResultWrapper
207 * @return array
208 * @throws DBUnexpectedError
209 */
210 function fetchRow( $res ) {
211 if ( $res instanceof ResultWrapper ) {
212 $res = $res->result;
213 }
214 wfSuppressWarnings();
215 $row = mysql_fetch_array( $res );
216 wfRestoreWarnings();
217 if ( $this->lastErrno() ) {
218 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
219 }
220 return $row;
221 }
222
223 /**
224 * @throws DBUnexpectedError
225 * @param $res ResultWrapper
226 * @return int
227 */
228 function numRows( $res ) {
229 if ( $res instanceof ResultWrapper ) {
230 $res = $res->result;
231 }
232 wfSuppressWarnings();
233 $n = mysql_num_rows( $res );
234 wfRestoreWarnings();
235 if( $this->lastErrno() ) {
236 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
237 }
238 return $n;
239 }
240
241 /**
242 * @param $res ResultWrapper
243 * @return int
244 */
245 function numFields( $res ) {
246 if ( $res instanceof ResultWrapper ) {
247 $res = $res->result;
248 }
249 return mysql_num_fields( $res );
250 }
251
252 /**
253 * @param $res ResultWrapper
254 * @param $n string
255 * @return string
256 */
257 function fieldName( $res, $n ) {
258 if ( $res instanceof ResultWrapper ) {
259 $res = $res->result;
260 }
261 return mysql_field_name( $res, $n );
262 }
263
264 /**
265 * @return int
266 */
267 function insertId() {
268 return mysql_insert_id( $this->mConn );
269 }
270
271 /**
272 * @param $res ResultWrapper
273 * @param $row
274 * @return bool
275 */
276 function dataSeek( $res, $row ) {
277 if ( $res instanceof ResultWrapper ) {
278 $res = $res->result;
279 }
280 return mysql_data_seek( $res, $row );
281 }
282
283 /**
284 * @return int
285 */
286 function lastErrno() {
287 if ( $this->mConn ) {
288 return mysql_errno( $this->mConn );
289 } else {
290 return mysql_errno();
291 }
292 }
293
294 /**
295 * @return string
296 */
297 function lastError() {
298 if ( $this->mConn ) {
299 # Even if it's non-zero, it can still be invalid
300 wfSuppressWarnings();
301 $error = mysql_error( $this->mConn );
302 if ( !$error ) {
303 $error = mysql_error();
304 }
305 wfRestoreWarnings();
306 } else {
307 $error = mysql_error();
308 }
309 if( $error ) {
310 $error .= ' (' . $this->mServer . ')';
311 }
312 return $error;
313 }
314
315 /**
316 * @return int
317 */
318 function affectedRows() {
319 return mysql_affected_rows( $this->mConn );
320 }
321
322 /**
323 * @param $table string
324 * @param $uniqueIndexes
325 * @param $rows array
326 * @param $fname string
327 * @return ResultWrapper
328 */
329 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
330 return $this->nativeReplace( $table, $rows, $fname );
331 }
332
333 /**
334 * Estimate rows in dataset
335 * Returns estimated count, based on EXPLAIN output
336 * Takes same arguments as Database::select()
337 *
338 * @param $table string|array
339 * @param $vars string|array
340 * @param $conds string|array
341 * @param $fname string
342 * @param $options string|array
343 * @return int
344 */
345 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
346 $options['EXPLAIN'] = true;
347 $res = $this->select( $table, $vars, $conds, $fname, $options );
348 if ( $res === false ) {
349 return false;
350 }
351 if ( !$this->numRows( $res ) ) {
352 return 0;
353 }
354
355 $rows = 1;
356 foreach ( $res as $plan ) {
357 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
358 }
359 return $rows;
360 }
361
362 /**
363 * @param $table string
364 * @param $field string
365 * @return bool|MySQLField
366 */
367 function fieldInfo( $table, $field ) {
368 $table = $this->tableName( $table );
369 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
370 if ( !$res ) {
371 return false;
372 }
373 $n = mysql_num_fields( $res->result );
374 for( $i = 0; $i < $n; $i++ ) {
375 $meta = mysql_fetch_field( $res->result, $i );
376 if( $field == $meta->name ) {
377 return new MySQLField($meta);
378 }
379 }
380 return false;
381 }
382
383 /**
384 * Get information about an index into an object
385 * Returns false if the index does not exist
386 *
387 * @param $table string
388 * @param $index string
389 * @param $fname string
390 * @return bool|array|null False or null on failure
391 */
392 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
393 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
394 # SHOW INDEX should work for 3.x and up:
395 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
396 $table = $this->tableName( $table );
397 $index = $this->indexName( $index );
398 $sql = 'SHOW INDEX FROM ' . $table;
399 $res = $this->query( $sql, $fname );
400
401 if ( !$res ) {
402 return null;
403 }
404
405 $result = array();
406
407 foreach ( $res as $row ) {
408 if ( $row->Key_name == $index ) {
409 $result[] = $row;
410 }
411 }
412
413 return empty( $result ) ? false : $result;
414 }
415
416 /**
417 * @param $db
418 * @return bool
419 */
420 function selectDB( $db ) {
421 $this->mDBname = $db;
422 return mysql_select_db( $db, $this->mConn );
423 }
424
425 /**
426 * @param $s string
427 *
428 * @return string
429 */
430 function strencode( $s ) {
431 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
432
433 if($sQuoted === false) {
434 $this->ping();
435 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
436 }
437 return $sQuoted;
438 }
439
440 /**
441 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
442 *
443 * @param $s string
444 *
445 * @return string
446 */
447 public function addIdentifierQuotes( $s ) {
448 return "`" . $this->strencode( $s ) . "`";
449 }
450
451 /**
452 * @param $name string
453 * @return bool
454 */
455 public function isQuotedIdentifier( $name ) {
456 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
457 }
458
459 /**
460 * @return bool
461 */
462 function ping() {
463 $ping = mysql_ping( $this->mConn );
464 if ( $ping ) {
465 return true;
466 }
467
468 mysql_close( $this->mConn );
469 $this->mOpened = false;
470 $this->mConn = false;
471 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
472 return true;
473 }
474
475 /**
476 * Returns slave lag.
477 *
478 * This will do a SHOW SLAVE STATUS
479 *
480 * @return int
481 */
482 function getLag() {
483 if ( !is_null( $this->mFakeSlaveLag ) ) {
484 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
485 return $this->mFakeSlaveLag;
486 }
487
488 return $this->getLagFromSlaveStatus();
489 }
490
491 /**
492 * @return bool|int
493 */
494 function getLagFromSlaveStatus() {
495 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
496 if ( !$res ) {
497 return false;
498 }
499 $row = $res->fetchObject();
500 if ( !$row ) {
501 return false;
502 }
503 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
504 return false;
505 } else {
506 return intval( $row->Seconds_Behind_Master );
507 }
508 }
509
510 /**
511 * @deprecated in 1.19, use getLagFromSlaveStatus
512 *
513 * @return bool|int
514 */
515 function getLagFromProcesslist() {
516 wfDeprecated( __METHOD__, '1.19' );
517 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
518 if( !$res ) {
519 return false;
520 }
521 # Find slave SQL thread
522 foreach( $res as $row ) {
523 /* This should work for most situations - when default db
524 * for thread is not specified, it had no events executed,
525 * and therefore it doesn't know yet how lagged it is.
526 *
527 * Relay log I/O thread does not select databases.
528 */
529 if ( $row->User == 'system user' &&
530 $row->State != 'Waiting for master to send event' &&
531 $row->State != 'Connecting to master' &&
532 $row->State != 'Queueing master event to the relay log' &&
533 $row->State != 'Waiting for master update' &&
534 $row->State != 'Requesting binlog dump' &&
535 $row->State != 'Waiting to reconnect after a failed master event read' &&
536 $row->State != 'Reconnecting after a failed master event read' &&
537 $row->State != 'Registering slave on master'
538 ) {
539 # This is it, return the time (except -ve)
540 if ( $row->Time > 0x7fffffff ) {
541 return false;
542 } else {
543 return $row->Time;
544 }
545 }
546 }
547 return false;
548 }
549
550 /**
551 * Wait for the slave to catch up to a given master position.
552 *
553 * @param $pos DBMasterPos object
554 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
555 * @return bool|string
556 */
557 function masterPosWait( DBMasterPos $pos, $timeout ) {
558 $fname = 'DatabaseBase::masterPosWait';
559 wfProfileIn( $fname );
560
561 # Commit any open transactions
562 if ( $this->mTrxLevel ) {
563 $this->commit( __METHOD__ );
564 }
565
566 if ( !is_null( $this->mFakeSlaveLag ) ) {
567 $status = parent::masterPosWait( $pos, $timeout );
568 wfProfileOut( $fname );
569 return $status;
570 }
571
572 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
573 $encFile = $this->addQuotes( $pos->file );
574 $encPos = intval( $pos->pos );
575 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
576 $res = $this->doQuery( $sql );
577
578 if ( $res && $row = $this->fetchRow( $res ) ) {
579 wfProfileOut( $fname );
580 return $row[0];
581 } else {
582 wfProfileOut( $fname );
583 return false;
584 }
585 }
586
587 /**
588 * Get the position of the master from SHOW SLAVE STATUS
589 *
590 * @return MySQLMasterPos|bool
591 */
592 function getSlavePos() {
593 if ( !is_null( $this->mFakeSlaveLag ) ) {
594 return parent::getSlavePos();
595 }
596
597 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
598 $row = $this->fetchObject( $res );
599
600 if ( $row ) {
601 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
602 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
603 } else {
604 return false;
605 }
606 }
607
608 /**
609 * Get the position of the master from SHOW MASTER STATUS
610 *
611 * @return MySQLMasterPos|bool
612 */
613 function getMasterPos() {
614 if ( $this->mFakeMaster ) {
615 return parent::getMasterPos();
616 }
617
618 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
619 $row = $this->fetchObject( $res );
620
621 if ( $row ) {
622 return new MySQLMasterPos( $row->File, $row->Position );
623 } else {
624 return false;
625 }
626 }
627
628 /**
629 * @return string
630 */
631 function getServerVersion() {
632 return mysql_get_server_info( $this->mConn );
633 }
634
635 /**
636 * @param $index
637 * @return string
638 */
639 function useIndexClause( $index ) {
640 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
641 }
642
643 /**
644 * @return string
645 */
646 function lowPriorityOption() {
647 return 'LOW_PRIORITY';
648 }
649
650 /**
651 * @return string
652 */
653 public static function getSoftwareLink() {
654 return '[http://www.mysql.com/ MySQL]';
655 }
656
657 /**
658 * @return bool
659 */
660 function standardSelectDistinct() {
661 return false;
662 }
663
664 /**
665 * @param $options array
666 */
667 public function setSessionOptions( array $options ) {
668 if ( isset( $options['connTimeout'] ) ) {
669 $timeout = (int)$options['connTimeout'];
670 $this->query( "SET net_read_timeout=$timeout" );
671 $this->query( "SET net_write_timeout=$timeout" );
672 }
673 }
674
675 public function streamStatementEnd( &$sql, &$newLine ) {
676 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
677 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
678 $this->delimiter = $m[1];
679 $newLine = '';
680 }
681 return parent::streamStatementEnd( $sql, $newLine );
682 }
683
684 /**
685 * @param $lockName string
686 * @param $method string
687 * @param $timeout int
688 * @return bool
689 */
690 public function lock( $lockName, $method, $timeout = 5 ) {
691 $lockName = $this->addQuotes( $lockName );
692 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
693 $row = $this->fetchObject( $result );
694
695 if( $row->lockstatus == 1 ) {
696 return true;
697 } else {
698 wfDebug( __METHOD__." failed to acquire lock\n" );
699 return false;
700 }
701 }
702
703 /**
704 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
705 * @param $lockName string
706 * @param $method string
707 * @return bool
708 */
709 public function unlock( $lockName, $method ) {
710 $lockName = $this->addQuotes( $lockName );
711 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
712 $row = $this->fetchObject( $result );
713 return $row->lockstatus;
714 }
715
716 /**
717 * @param $read array
718 * @param $write array
719 * @param $method string
720 * @param $lowPriority bool
721 */
722 public function lockTables( $read, $write, $method, $lowPriority = true ) {
723 $items = array();
724
725 foreach( $write as $table ) {
726 $tbl = $this->tableName( $table ) .
727 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
728 ' WRITE';
729 $items[] = $tbl;
730 }
731 foreach( $read as $table ) {
732 $items[] = $this->tableName( $table ) . ' READ';
733 }
734 $sql = "LOCK TABLES " . implode( ',', $items );
735 $this->query( $sql, $method );
736 }
737
738 /**
739 * @param $method string
740 */
741 public function unlockTables( $method ) {
742 $this->query( "UNLOCK TABLES", $method );
743 }
744
745 /**
746 * Get search engine class. All subclasses of this
747 * need to implement this if they wish to use searching.
748 *
749 * @return String
750 */
751 public function getSearchEngine() {
752 return 'SearchMySQL';
753 }
754
755 /**
756 * @param bool $value
757 * @return mixed
758 */
759 public function setBigSelects( $value = true ) {
760 if ( $value === 'default' ) {
761 if ( $this->mDefaultBigSelects === null ) {
762 # Function hasn't been called before so it must already be set to the default
763 return;
764 } else {
765 $value = $this->mDefaultBigSelects;
766 }
767 } elseif ( $this->mDefaultBigSelects === null ) {
768 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
769 }
770 $encValue = $value ? '1' : '0';
771 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
772 }
773
774 /**
775 * DELETE where the condition is a join. MySql uses multi-table deletes.
776 * @param $delTable string
777 * @param $joinTable string
778 * @param $delVar string
779 * @param $joinVar string
780 * @param $conds array|string
781 * @param $fname bool
782 * @return bool|ResultWrapper
783 */
784 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
785 if ( !$conds ) {
786 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
787 }
788
789 $delTable = $this->tableName( $delTable );
790 $joinTable = $this->tableName( $joinTable );
791 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
792
793 if ( $conds != '*' ) {
794 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
795 }
796
797 return $this->query( $sql, $fname );
798 }
799
800 /**
801 * Determines how long the server has been up
802 *
803 * @return int
804 */
805 function getServerUptime() {
806 $vars = $this->getMysqlStatus( 'Uptime' );
807 return (int)$vars['Uptime'];
808 }
809
810 /**
811 * Determines if the last failure was due to a deadlock
812 *
813 * @return bool
814 */
815 function wasDeadlock() {
816 return $this->lastErrno() == 1213;
817 }
818
819 /**
820 * Determines if the last failure was due to a lock timeout
821 *
822 * @return bool
823 */
824 function wasLockTimeout() {
825 return $this->lastErrno() == 1205;
826 }
827
828 /**
829 * Determines if the last query error was something that should be dealt
830 * with by pinging the connection and reissuing the query
831 *
832 * @return bool
833 */
834 function wasErrorReissuable() {
835 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
836 }
837
838 /**
839 * Determines if the last failure was due to the database being read-only.
840 *
841 * @return bool
842 */
843 function wasReadOnlyError() {
844 return $this->lastErrno() == 1223 ||
845 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
846 }
847
848 /**
849 * @param $oldName
850 * @param $newName
851 * @param $temporary bool
852 * @param $fname string
853 */
854 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
855 $tmp = $temporary ? 'TEMPORARY ' : '';
856 $newName = $this->addIdentifierQuotes( $newName );
857 $oldName = $this->addIdentifierQuotes( $oldName );
858 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
859 $this->query( $query, $fname );
860 }
861
862 /**
863 * List all tables on the database
864 *
865 * @param $prefix string Only show tables with this prefix, e.g. mw_
866 * @param $fname String: calling function name
867 * @return array
868 */
869 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
870 $result = $this->query( "SHOW TABLES", $fname);
871
872 $endArray = array();
873
874 foreach( $result as $table ) {
875 $vars = get_object_vars($table);
876 $table = array_pop( $vars );
877
878 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
879 $endArray[] = $table;
880 }
881 }
882
883 return $endArray;
884 }
885
886 /**
887 * @param $tableName
888 * @param $fName string
889 * @return bool|ResultWrapper
890 */
891 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
892 if( !$this->tableExists( $tableName, $fName ) ) {
893 return false;
894 }
895 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
896 }
897
898 /**
899 * @return array
900 */
901 protected function getDefaultSchemaVars() {
902 $vars = parent::getDefaultSchemaVars();
903 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
904 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
905 return $vars;
906 }
907
908 /**
909 * Get status information from SHOW STATUS in an associative array
910 *
911 * @param $which string
912 * @return array
913 */
914 function getMysqlStatus( $which = "%" ) {
915 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
916 $status = array();
917
918 foreach ( $res as $row ) {
919 $status[$row->Variable_name] = $row->Value;
920 }
921
922 return $status;
923 }
924
925 }
926
927 /**
928 * Legacy support: Database == DatabaseMysql
929 *
930 * @deprecated in 1.16
931 */
932 class Database extends DatabaseMysql {}
933
934 /**
935 * Utility class.
936 * @ingroup Database
937 */
938 class MySQLField implements Field {
939 private $name, $tablename, $default, $max_length, $nullable,
940 $is_pk, $is_unique, $is_multiple, $is_key, $type;
941
942 function __construct ( $info ) {
943 $this->name = $info->name;
944 $this->tablename = $info->table;
945 $this->default = $info->def;
946 $this->max_length = $info->max_length;
947 $this->nullable = !$info->not_null;
948 $this->is_pk = $info->primary_key;
949 $this->is_unique = $info->unique_key;
950 $this->is_multiple = $info->multiple_key;
951 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
952 $this->type = $info->type;
953 }
954
955 /**
956 * @return string
957 */
958 function name() {
959 return $this->name;
960 }
961
962 /**
963 * @return string
964 */
965 function tableName() {
966 return $this->tableName;
967 }
968
969 /**
970 * @return string
971 */
972 function type() {
973 return $this->type;
974 }
975
976 /**
977 * @return bool
978 */
979 function isNullable() {
980 return $this->nullable;
981 }
982
983 function defaultValue() {
984 return $this->default;
985 }
986
987 /**
988 * @return bool
989 */
990 function isKey() {
991 return $this->is_key;
992 }
993
994 /**
995 * @return bool
996 */
997 function isMultipleKey() {
998 return $this->is_multiple;
999 }
1000 }
1001
1002 class MySQLMasterPos implements DBMasterPos {
1003 var $file, $pos;
1004
1005 function __construct( $file, $pos ) {
1006 $this->file = $file;
1007 $this->pos = $pos;
1008 }
1009
1010 function __toString() {
1011 return "{$this->file}/{$this->pos}";
1012 }
1013 }